using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

public class ItemEditor : EditorWindow
{
    //默认写法，修改CardDataListSO就行
    private CardDataListSO dataBase;
    //默认写法，修改CardDataDetails就行
    private List<CardDataDetails> itemList = new();
    //默认写法，不需要修改
    private VisualTreeAsset itemRowTemplate;
    //默认写法，不需要修改，左边ListView（VisualElement）
    private ListView itemListView;
    //默认写法，不需要修改，右边的ScrollView
    private ScrollView itemDetailsSection;
    //默认写法，修改CardDataDetails就行,当前选中的Item的数据
    private CardDataDetails activeItem;

    //默认预览图片
    private Sprite defaultIcon;
    
    //默认写法，不需要修改，右边的Icon
    private VisualElement iconPreview;
    

    [MenuItem("Cola/ItemEditor")]
    public static void ShowExample()
    {
        ItemEditor wnd = GetWindow<ItemEditor>();
        wnd.titleContent = new GUIContent("ItemEditor");
    }

    public void CreateGUI()
    {
        // Each editor window contains a root VisualElement object
        VisualElement root = rootVisualElement;

        // VisualElements objects can contain other VisualElement following a tree hierarchy.
        // VisualElement label = new Label("Hello World! From C#");
        // root.Add(label);

        // Import UXML
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/Editor/UI Builder/ItemEditor.uxml");
        VisualElement labelFromUXML = visualTree.Instantiate();
        root.Add(labelFromUXML);

        //拿到模版数据
        itemRowTemplate = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/Editor/UI Builder/ItemRowTemplate.uxml");

        //拿默认Icon图片，根据实际需求来写
        defaultIcon = AssetDatabase.LoadAssetAtPath<Sprite>("Assets/Art/Card/card_background.png");

        //默认写法，不需要修改，变量赋值
        itemListView = root.Q<VisualElement>("ItemList").Q<ListView>("ListView");
        itemDetailsSection = root.Q<ScrollView>("ItemDetails");
        iconPreview = itemDetailsSection.Q<VisualElement>("Icon");


        //获得按键
        root.Q<Button>("AddButton").clicked += OnAddItemClicked;
        root.Q<Button>("DeleteButton").clicked += OnDeleteClicked;
        //加载数据
        LoadDataBase();

        //生成ListView
        GenerateListView();
    }

    #region 按键事件
    //默认写法
    private void OnDeleteClicked()
    {
        itemList.Remove(activeItem);
        itemListView.Rebuild();
        itemDetailsSection.visible = false;
    }
    //默认写法，修改CardDataDetails就行
    private void OnAddItemClicked()
    {
        CardDataDetails newItem = new CardDataDetails();
        newItem.cardName = "NEW CARD";
        newItem.cardID = 1001 + itemList.Count;
        itemList.Add(newItem);
        itemListView.Rebuild();
    }
    #endregion

    private void LoadDataBase()
    {
        //默认写法，修改CardDataListSO就行
        var dataArray = AssetDatabase.FindAssets("CardDataListSO");
        //默认写法，修改CardDataListSO就行
        if (dataArray.Length > 1)
        {
            var path = AssetDatabase.GUIDToAssetPath(dataArray[0]);
            dataBase = AssetDatabase.LoadAssetAtPath(path, typeof(CardDataListSO)) as CardDataListSO;
        }
        //赋值，默认写法
        itemList = dataBase.cardDataList;
        
        //如果不标记则无法保存数据，默认写法
        EditorUtility.SetDirty(dataBase);
        
        //Debug.Log(itemList[0].cardName);
    }

    private void GenerateListView()
    {
        //默认写法
        Func<VisualElement> makeItem = () => itemRowTemplate.CloneTree();
        //默认写法
        Action<VisualElement, int> bindItem = (e, i) =>
        {
            //默认写法，根据实际需求来写
            if (i < itemList.Count)
            {
                
                if (itemList[i].cardImage != null)
                    e.Q<VisualElement>("Icon").style.backgroundImage = itemList[i].cardImage.texture;

                //根据实际需求来写
                string level = "";
                if (itemList[i].isPrimaryCard == true)
                    level = "初级·";
                else if (itemList[i].isIntermediateCard == true)
                    level = "中级·";
                else if (itemList[i].isSeniorCard == true)
                    level = "高级·";
                
                e.Q<Label>("Name").text = itemList[i] == null ? "NO CARD" 
                    : level+itemList[i].cardName;
            }
        };
        //根据需要高度调整数值
        itemListView.fixedItemHeight = 50;  
        //默认写法
        itemListView.itemsSource = itemList;
        itemListView.makeItem = makeItem;
        itemListView.bindItem = bindItem;
        //默认写法
        itemListView.onSelectionChange += OnListSelectionChange;
    
        //默认写法,右侧信息面板不可见
        itemDetailsSection.visible = false;
    }

    //默认写法，修改CardDataDetails就行
    private void OnListSelectionChange(IEnumerable<object> selectedItem)
    {
        activeItem = (CardDataDetails)selectedItem.First();
        GetItemDetails();
        itemDetailsSection.visible = true;
    }

    private void GetItemDetails()
    {
        //默认写法
        itemDetailsSection.MarkDirtyRepaint();

        itemDetailsSection.Q<IntegerField>("ItemID").value = activeItem.cardID;
        itemDetailsSection.Q<IntegerField>("ItemID").RegisterValueChangedCallback(evt =>
        {
            activeItem.cardID = evt.newValue;
        });

        itemDetailsSection.Q<TextField>("ItemName").value = activeItem.cardName;
        itemDetailsSection.Q<TextField>("ItemName").RegisterValueChangedCallback(evt =>
        {
            activeItem.cardName = evt.newValue;
            itemListView.Rebuild();
        });

        iconPreview.style.backgroundImage =
            activeItem.cardImage == null ? defaultIcon.texture : activeItem.cardImage.texture;
        itemDetailsSection.Q<ObjectField>("ItemIcon").value = activeItem.cardImage;
        itemDetailsSection.Q<ObjectField>("ItemIcon").RegisterValueChangedCallback(evt =>
        {
            Sprite newIcon = evt.newValue as Sprite;
            activeItem.cardImage = newIcon;

            iconPreview.style.backgroundImage = newIcon == null ? defaultIcon.texture : newIcon.texture;
            itemListView.Rebuild();
        });

        //其他所有变量的绑定
        // itemDetailsSection.Q<ObjectField>("ItemSprite").value = activeItem.itemOnWorldSprite;
        // itemDetailsSection.Q<ObjectField>("ItemSprite").RegisterValueChangedCallback(evt =>
        // {
        //     activeItem.itemOnWorldSprite = (Sprite)evt.newValue;
        // });


        itemDetailsSection.Q<ObjectField>("Effects").value = activeItem.effects;
        itemDetailsSection.Q<ObjectField>("Effects").RegisterValueChangedCallback(evt =>
        {
            activeItem.effects = (Effect)evt.newValue;
        });


        itemDetailsSection.Q<EnumField>("ItemType").Init(activeItem.cardType);
        itemDetailsSection.Q<EnumField>("ItemType").value = activeItem.cardType;
        itemDetailsSection.Q<EnumField>("ItemType").RegisterValueChangedCallback(evt =>
        {
            activeItem.cardType = (CardType)evt.newValue;
        });

        itemDetailsSection.Q<TextField>("Description").value = activeItem.cardDescription;
        itemDetailsSection.Q<TextField>("Description").RegisterValueChangedCallback(evt =>
        {
            activeItem.cardDescription = evt.newValue;
        });

        // itemDetailsSection.Q<IntegerField>("ItemUseRadius").value = activeItem.itemUseRadius;
        // itemDetailsSection.Q<IntegerField>("ItemUseRadius").RegisterValueChangedCallback(evt =>
        // {
        //     activeItem.itemUseRadius = evt.newValue;
        // });

        itemDetailsSection.Q<Toggle>("isPrimaryCard").value = activeItem.isPrimaryCard;
        itemDetailsSection.Q<Toggle>("isPrimaryCard").RegisterValueChangedCallback(evt =>
        {
            activeItem.isPrimaryCard = evt.newValue;
        });

        itemDetailsSection.Q<Toggle>("isIntermediateCard").value = activeItem.isIntermediateCard;
        itemDetailsSection.Q<Toggle>("isIntermediateCard").RegisterValueChangedCallback(evt =>
        {
            activeItem.isIntermediateCard = evt.newValue;
        });

        itemDetailsSection.Q<Toggle>("isSeniorCard").value = activeItem.isSeniorCard;
        itemDetailsSection.Q<Toggle>("isSeniorCard").RegisterValueChangedCallback(evt =>
        {
            activeItem.isSeniorCard = evt.newValue;
        });
        itemDetailsSection.Q<Toggle>("isCollected").value = activeItem.isCollected;
        itemDetailsSection.Q<Toggle>("isCollected").RegisterValueChangedCallback(evt =>
        {
            activeItem.isCollected = evt.newValue;
        });

        itemDetailsSection.Q<IntegerField>("CardCost").value = activeItem.cardCost;
        itemDetailsSection.Q<IntegerField>("CardCost").RegisterValueChangedCallback(evt =>
        {
            activeItem.cardCost = evt.newValue;
        });

        itemDetailsSection.Q<IntegerField>("Price").value = activeItem.cardPrice;
        itemDetailsSection.Q<IntegerField>("Price").RegisterValueChangedCallback(evt =>
        {
            activeItem.cardPrice = evt.newValue;
        });

        itemDetailsSection.Q<Slider>("SellPercentage").value = activeItem.sellPercentage;
        itemDetailsSection.Q<Slider>("SellPercentage").RegisterValueChangedCallback(evt =>
        {
            activeItem.sellPercentage = evt.newValue;
        });
    }
}